﻿function read(query, user, request) {

   var currentTime = new Date();
   
   request.execute({
       success: function (results) {
          
           if (results.length === 0) {
               request.respond();
               return;
           }

           var devicesTable = tables.getTable('Devices');
           var count = 0;
           results.forEach(function (message) {
               devicesTable
                   .where({ id: message.DeviceId })
                   .read({
                        success: function (devices) {
                            if (devices.length > 0) {
                                var device = devices[0];
                                message.SenderName = device.Name;
                                message.Color = device.Color;
                                message.CurrentServerTime = currentTime;
                            }
                            count++;
                            // console.log(count.toString(), message.Text);
                            if (count === results.length) {                
                                request.respond();
                            }
                        }
                    })
          });
       }
    });
}